<template>
  <div id="goodsDetail">
    <div class="goods-detail-main">
      <div
        style="
          margin: 10px 0;
          background-color: #f5f5f5;
          padding: 10px 20px;
          border-radius: 10px;
        "
      >
        <el-row>
          <el-col :span="2">
            <el-image
              :src="businessInfo?.avatar || TestGoods"
              fit="cover"
              style="width: 50px; height: 50px; border-radius: 10px"
            />
          </el-col>
          <el-col :span="12" style="display: flex">
            <el-space>
              <div style="margin: auto 0; font-size: 24px; font-weight: bolder">
                {{ businessInfo?.nickname }}
              </div>
              <el-rate
                v-model="value"
                disabled
                score-template="{value} 评分"
                show-score
                style="margin: auto 0"
                text-color="#ff9900"
              />
            </el-space>
          </el-col>
          <el-col :span="4" />
          <el-col :span="6" style="display: flex">
            <el-space>
              <el-button type="success" @click="toView('viewBusiness')">
                查看店铺
              </el-button>
              <el-button type="primary" @click="toView('chat')">
                联系店家
              </el-button>
            </el-space>
          </el-col>
        </el-row>
      </div>

      <el-row :gutter="12" class="h-full">
        <!-- 轮播图 -->
        <el-col :span="9">
          <div>
            <el-carousel
              height="400px"
              indicator-position="none"
              style="border-radius: 16px"
            >
              <el-carousel-item
                v-for="item in goodsInfo?.mainImages"
                :key="item"
              >
                <el-image
                  :preview-src-list="goodsInfo?.mainImages"
                  :src="item"
                  fit="cover"
                  preview-teleported
                  style="width: 400px"
                />
              </el-carousel-item>
            </el-carousel>
          </div>
        </el-col>
        <!--  商品信息-->
        <el-col :span="14">
          <div>
            <el-text
              :line-clamp="2"
              style="font-size: 23px; font-weight: bolder"
            >
              {{ goodsInfo?.goodsName }}
            </el-text>

            <br />
          </div>
          <el-space direction="vertical" fill style="width: 100%">
            <el-text>总销量23</el-text>
            <el-space>
              <el-text> 价格</el-text>

              <el-text type="danger"
                >￥
                <el-text size="large" type="danger">
                  {{ selectSku?.scope * selectSku?.price }}
                </el-text>
              </el-text>

              <el-text v-if="selectSku?.scope !== 1" size="small" tag="del">
                ￥ {{ selectSku?.price }}
              </el-text>
              <el-text v-if="selectSku?.scope !== 1" type="danger">
                {{ selectSku?.scope * 10 }}折
              </el-text>
            </el-space>
            <div>
              分类:
              <el-text>{{ getGoodsTypeName(goodsInfo?.typeId) }}</el-text>
            </div>
            <div>
              配送至：
              <address-select />
            </div>

            <div>
              <div style="margin-bottom: 5px">规格：</div>
              <el-scrollbar height="150px">
                <div style="margin-bottom: 5px; padding: 10px">
                  <el-row
                    v-for="(item, index) in specList"
                    :key="item.value"
                    :gutter="6"
                    style="padding: 10px 0; border-bottom: solid 1px #f5f5f5"
                  >
                    <el-col :span="3">
                      <el-text size="small">{{ item.label }}</el-text>
                    </el-col>

                    <el-col :span="21">
                      <el-space size="small" wrap>
                        <el-text
                          v-for="ch in item.children"
                          :key="ch.value"
                          :class="
                            ch.value === selectSpec[index]
                              ? 'spec-text-click'
                              : ''
                          "
                          class="spec-text"
                          @click="handleSelectSpec(index, ch.value)"
                        >
                          <span style="">{{ ch.label }} </span>
                        </el-text>
                      </el-space>
                    </el-col>
                  </el-row>
                </div>
              </el-scrollbar>
            </div>
            <div>
              <el-space>
                <el-text> 数量：</el-text>
                <el-input-number
                  v-model="selectGoodsNum"
                  :max="selectSku.store"
                  :min="1"
                  size="small"
                />
                <el-text size="small" type="info">
                  库存 {{ selectSku?.store }}
                </el-text>
                <el-text size="small" type="info">
                  预存库存 {{ selectSku?.reservedStore }}
                </el-text>
              </el-space>
            </div>
          </el-space>

          <el-row :gutter="6" style="margin-top: 10px">
            <el-col :span="4">
              <div style="text-align: center">
                <el-tooltip content="收藏" effect="light" placement="bottom">
                  <span
                    :class="collectFlag ? 'collect-text-click' : ''"
                    class="icon-shoucang el-icon collect-text"
                    style="font-size: 32px"
                    @click="handleCollectFlag"
                  ></span>
                </el-tooltip>
              </div>
            </el-col>
            <el-col :span="20">
              <el-button-group class="ml-4" style="width: 100%">
                <el-button
                  color="#f7ba2a"
                  style="width: 50%; margin: 0 auto"
                  @click="handleAddCart"
                  :disabled="selectSku?.store <= 0"
                  ><span style="color: white"> 加入购物车 </span>
                </el-button>
                <el-button
                  :disabled="selectSku?.store <= 0"
                  style="width: 50%; margin: 0 auto"
                  type="primary"
                  @click="handelNewOrdersPay"
                  >立即购买
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-segmented
        id="segmented"
        ref="segmentedRef"
        v-model="segmented"
        :options="options"
        block
        style="margin-top: 20px; position: sticky; top: 0; z-index: 100"
        @change="handleChangeSegmented"
      >
        <template #default="{ item }">
          {{ item.label }}
        </template>
      </el-segmented>
      <div style="display: flex">
        <div style="width: 750px">
          <div id="one1">
            <div
              style="
                padding-top: 40px;
                font-size: 24px;
                font-weight: bolder;
                margin-bottom: 10px;
              "
            >
              全部评论
            </div>
            <div v-for="i in 7" :key="i" class="comment">
              <!-- 头像-->
              <div style="display: flex; align-items: center">
                <el-space>
                  <el-avatar
                    :size="30"
                    :src="TestGoods"
                    style="display: block"
                  />
                  <el-text>这是用户1</el-text>
                  <el-text>{{ getTime() }}</el-text>
                </el-space>
              </div>
              <!-- 正文-->
              <div>
                <el-space>
                  <el-rate :model-value="3" disabled size="large" />
                  <el-text>已购买【玫瑰花，是多】</el-text>
                </el-space>
              </div>
              <!-- 文字-->

              <div class="comment-text" style="text-indent: 2em">
                >text-indent: 2em;text-indent: 2em;text-indent: 2em;text-indent:
                2em;
              </div>
              <!-- 商品图片-->
              <div>
                <el-row :gutter="12">
                  <el-col v-for="i in 7" :key="i" :span="4">
                    <el-image
                      :preview-src-list="[TestGoods]"
                      :src="TestGoods"
                      preview-teleported
                      style="border-radius: 10px"
                    />
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
          <div id="one2">
            <div
              style="
                padding-top: 40px;
                font-size: 24px;
                font-weight: bolder;
                margin-bottom: 10px;
              "
            >
              配置信息
            </div>
            <el-descriptions :column="2" border class="margin-top" size="small">
              <el-descriptions-item
                v-for="item in goodsInfo?.properties"
                :key="item.name"
                :label-width="100"
                :width="200"
                align="center"
              >
                <template #label>
                  <el-text>
                    {{ item.name }}
                  </el-text>
                </template>
                <el-text>
                  {{ item.value }}
                </el-text>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div id="one3">
            <div
              style="
                padding-top: 40px;
                font-size: 24px;
                font-weight: bolder;
                margin-bottom: 10px;
              "
            >
              图文介绍
            </div>
            <img
              v-for="item in goodsInfo?.imageDesc"
              :key="item"
              :src="item"
              alt=""
              style="display: block; width: 750px"
            />
          </div>

          <div id="one4">
            <div
              style="
                padding-top: 40px;
                font-size: 24px;
                font-weight: bolder;
                margin-bottom: 10px;
              "
            >
              商品推荐
            </div>
            <like-goods-view :span="6"></like-goods-view>
          </div>
        </div>
        <div style="flex: 1">
          <div
            style="
              width: 100%;
              padding-left: 20px;
              margin: 400px auto 0;
              position: sticky;
              top: 150px;
            "
          >
            <el-card shadow="hover">
              <el-row :gutter="12">
                <!--图片-->
                <el-col :span="10">
                  <el-image
                    :preview-src-list="
                      selectSku.image
                        ? [selectSku.image]
                        : goodsInfo?.mainImages
                    "
                    :src="selectSku.image || goodsInfo?.mainImages[0]"
                    preview-teleported
                    style="border-radius: 5px; width: 100px; height: 100px"
                  />
                </el-col>
                <el-col :span="13">
                  <div>￥ {{ selectSku.price }}</div>
                  <el-text size="small">商品编号：{{ selectSku?.id }}</el-text>
                  <!--<div style="margin: 5px 0; background-color: #f4f4f5">-->
                  <!--  <span style="color: #c8c9cc; font-size: 10px">已选： </span>-->
                  <!--  <span-->
                  <!--    v-for="i in 3"-->
                  <!--    :key="i"-->
                  <!--    style="color: #c8c9cc; font-size: 10px"-->
                  <!--  >-->
                  <!--    Option A</span-->
                  <!--  >-->
                  <!--</div>-->
                </el-col>
              </el-row>
              <el-row :gutter="4" style="margin: 5px 0">
                <el-col :span="4">
                  <el-text :line-clamp="1" size="small">配送至</el-text>
                </el-col>
                <el-col :span="18">
                  <address-select />
                </el-col>
                <!--<el-col :span="2">-->
                <!--  <el-tooltip-->
                <!--    content="选择其他地址"-->
                <!--    effect="light"-->
                <!--    placement="right"-->
                <!--  >-->
                <!--    <el-link-->
                <!--      :underline="false"-->
                <!--      class="icon-gengduo el-icon"-->
                <!--    ></el-link>-->
                <!--  </el-tooltip>-->
                <!--</el-col>-->
              </el-row>
              <el-scrollbar max-height="200px">
                <div
                  v-for="(item, index) in specList"
                  :key="item.value"
                  style="margin: 10px 0"
                >
                  <el-text style="margin-bottom: 10px; display: block"
                    >{{ item.label }}
                  </el-text>

                  <el-space size="small" wrap>
                    <span
                      v-for="ch in item.children"
                      :key="ch.value"
                      :class="
                        ch.value === selectSpec[index] ? 'spec-text-click' : ''
                      "
                      class="spec-text"
                      @click="handleSelectSpec(index, ch.value)"
                    >
                      {{ ch.label }}
                    </span>
                  </el-space>
                </div>
              </el-scrollbar>

              <div>
                <el-space>
                  <el-text> 数量：</el-text>
                  <el-input-number
                    v-if="selectSku.store > 0"
                    v-model="selectGoodsNum"
                    :max="selectSku.store"
                    :min="1"
                    size="small"
                  />
                  <el-text size="small" type="info">
                    库存 {{ selectSku?.store }}
                  </el-text>
                </el-space>
              </div>
              <el-row :gutter="6" style="margin-top: 10px">
                <el-col :span="4">
                  <div style="text-align: center">
                    <el-tooltip
                      content="收藏"
                      effect="light"
                      placement="bottom"
                    >
                      <span
                        :class="collectFlag ? 'collect-text-click' : ''"
                        class="icon-shoucang el-icon collect-text"
                        style="font-size: 32px"
                        @click="handleCollectFlag"
                      ></span>
                    </el-tooltip>
                  </div>
                </el-col>
                <el-col :span="20">
                  <el-button-group class="ml-4" style="width: 100%">
                    <el-button
                      color="#f7ba2a"
                      style="width: 50%; margin: 0 auto"
                      @click="handleAddCart"
                      :disabled="selectSku?.store <= 0"
                      ><span style="color: white"> 加入购物车 </span>
                    </el-button>
                    <el-button
                      :disabled="selectSku?.store <= 0"
                      style="width: 50%; margin: 0 auto"
                      type="primary"
                      @click="handelNewOrdersPay"
                      >立即购买
                    </el-button>
                  </el-button-group>
                </el-col>
              </el-row>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import TestGoods from "@/assets/testGoods.jpg";
import Img from "@/assets/testGoods.jpg";
import { nextTick, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  AddressControllerService,
  AddressVO,
  CartControllerService,
  CommonUserInfoVO,
  GoodsControllerService,
  GoodsSkuControllerService,
  GoodsSkuVO,
  GoodsSpecControllerService,
  GoodsTypeControllerService,
  GoodsTypeOption,
  GoodsVO,
  OrdersControllerService,
  TreeVO,
  UpdateStatusDTO,
  UserCollectControllerService,
} from "@/api";
import { ElMessage } from "element-plus";
import { useHistoryStore } from "@/store/modules/history";
import AddressSelect from "@/components/AddressSelect.vue";
import LikeGoodsView from "@/components/LikeGoodsView.vue";
// 获取路由
const route = useRoute();
const goodsId = ref();
const businessInfo = ref<CommonUserInfoVO>({});
// 添加历史记录信息
const useHistory = useHistoryStore();

// 获取商品的商家信息
async function getBusinessById() {
  await GoodsControllerService.getBusinessInfoByIdUsingGet1(goodsId.value).then(
    (res) => {
      businessInfo.value = res.data || {};
    }
  );
}

//获取商品基本信息
const goodsInfo = ref<GoodsVO>();

async function getGoodsInfo() {
  await GoodsControllerService.getGoodsInfoByIdUsingGet(goodsId.value).then(
    (res) => {
      goodsInfo.value = res.data;
    }
  );
}

//获取商品分类
const goodsTypeList = ref<Array<GoodsTypeOption>>();

function getGoodsType() {
  GoodsTypeControllerService.getGoodsTypeOptionUsingGet().then((res) => {
    goodsTypeList.value = res.data;
  });
}

function getGoodsTypeName(list: number[]) {
  if (!list || list.length === 0) return "无";
  //查找父分类
  const goodsType: GoodsTypeOption =
    goodsTypeList.value?.find((item) => item.value === list[0]) || {};
  let str = goodsType.label;
  if (list.length > 1) {
    //查找子分类
    const ch: GoodsTypeOption =
      goodsType.children?.find((item) => item.value === list[1]) || {};
    str = str + " / " + ch.label;
  }
  return str;
}

//获取地址
const addressList = ref<AddressVO[]>([]);

async function getAddressList() {
  AddressControllerService.getAddressListUsingGet().then((res) => {
    addressList.value = res.data || [];
  });
}

const popoverVisible = ref(false);
const selectAddIndex = ref(0); //选中的地址索引
//选中的地址索引
function selectAddress(index: number) {
  selectAddIndex.value = index;
  nextTick(() => {
    //   关闭弹窗
    popoverVisible.value = false;
  });
}

// 获取规格信息
const specList = ref<TreeVO[]>([]);
// 选择的规格信息
const selectSpec = ref<number[]>([]);

async function getSpecList() {
  selectSpec.value = [];
  GoodsSpecControllerService.getGoodsSpecAllUsingGet(goodsId.value).then(
    (res) => {
      specList.value = res.data || [];
      specList.value.forEach((item) => {
        selectSpec.value.push(item.children[0].value);
      });
    }
  );
}

// 选择规格事件
function handleSelectSpec(index: number, id: number) {
  let specTmp = [...selectSpec.value];
  specTmp[index] = id;
  console.log(specTmp);
  //判断选择的sku信息
  const tmp = goodsSkuList.value.find(
    (item) => item.specList.join("") === specTmp.join("")
  );
  // 如果存在才改变，不然不改变
  if (tmp) {
    selectSku.value = tmp;
    selectSpec.value[index] = id;
  } else {
    ElMessage.warning("当前规格没有对应的SKU信息");
  }
}

// 获取sku信息
const goodsSkuList = ref<GoodsSkuVO[]>([]);
const selectSku = ref<GoodsSkuVO>({});

function getGoodsSku() {
  GoodsSkuControllerService.getGoodsSkuAllUsingGet(goodsId.value).then(
    (res) => {
      goodsSkuList.value = res.data || [];
      selectSku.value = res!.data[0];
    }
  );
}

// 选择的数量
const selectGoodsNum = ref(1);

//加入购物车
function handleAddCart() {
  const data: UpdateStatusDTO = {
    id: selectSku.value.id,
    status: selectGoodsNum.value,
  };
  // 添加购物车
  CartControllerService.insertCartUsingPost(data).then((res) => {
    ElMessage.success(res.data);
    selectSku.value.reservedStore += selectGoodsNum.value;
    selectSku.value.store -= selectGoodsNum.value;
  });
}

// 立即下单
function handelNewOrdersPay() {
  //判断选择的skuid
  if (!selectGoodsNum.value || selectGoodsNum.value < 1 || !selectSku.value) {
    ElMessage.warning("请选择规格后再下单");
    return;
  }
  if (selectSku.value?.store <= 0) {
    ElMessage.warning("库存为0，无法下单");
    return;
  }
  OrdersControllerService.newOrderPayUsingPost(
    businessInfo.value.id!,
    selectGoodsNum.value,
    selectSku.value.id!
  ).then((res) => {
    //跳转订单结算页
    router.push(`/orders_pay/${res.data}`);
  });
}

//判断是否收藏
const collectFlag = ref(false);

function getCollectFlag() {
  UserCollectControllerService.getCollectFlagUsingDelete(goodsId.value).then(
    (res) => {
      collectFlag.value = res.data || false;
    }
  );
}

function handleCollectFlag() {
  if (collectFlag.value) {
    UserCollectControllerService.delUserCollectUsingDelete([
      goodsId.value,
    ]).then((res) => {
      ElMessage.success(res.data);
      collectFlag.value = false;
    });
  } else {
    UserCollectControllerService.insertUserCollectUsingPost(goodsId.value).then(
      (res) => {
        ElMessage.success(res.data);
        collectFlag.value = true;
      }
    );
  }
}

function getAllDate() {
  getBusinessById();
  getGoodsInfo();
  getAddressList();
  getSpecList();
  getCollectFlag();
  getGoodsSku();
  getGoodsType();
}

const value = ref(3.7);
const segmented = ref(1);
const segmentedRef = ref();
const options = [
  { label: "商品评论", value: 1 },
  { label: "配置信息", value: 2 },
  { label: "图文介绍", value: 3 },
  { label: "商品推荐", value: 4 },
];

//路由跳转
const router = useRouter();

function toView(type: string) {
  switch (type) {
    case "view":
    case "chat": {
      router.push({
        path: "/chat",
        query: {
          businessId: businessInfo.value.id,
        },
      });
    }
  }
}

function getTime() {
  return new Date().toLocaleDateString();
}

function handleChangeSegmented(data: any) {
  window.location.href = window.location.href.split("#")[0] + "#one" + data;
}

watch(
  () => route.params,
  () => {
    if (route.params.goodsId && route.params.goodsId !== goodsId.value) {
      goodsId.value = route.params.goodsId;
      useHistory.addHistory(goodsId.value);
      getAllDate();
      document.documentElement.scrollTop = 0;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
onMounted(() => {
  //拿到子元素的高度
  const box = document.querySelector(".goods-detail-main");
  // const one = document.querySelector("#one1");
  // const one2 = document.querySelector("#one2");
  // const one3 = document.querySelector("#one3");
  // ElMessage.success(box, box.scrollHeight);
  //将子元素的高度赋予父元素
  const goodsDetailDom = document.querySelector("#goodsDetail");
  goodsDetailDom.style.height = box.offsetHeight + "px";
});
</script>

<style lang="scss" scoped>
#goodsDetail {
  display: flex;

  .goods-detail-main {
    width: 75%;
    position: absolute;
    left: 13%;

    .collect-text {
      &:hover {
        color: #409eff;
      }
    }

    .collect-text-click {
      color: #409eff;
    }
  }

  .comment {
    height: 100%;
    border-top: solid 1px #f5f5f5;

    margin: 5px 0;
    padding: 10px 5px;

    .comment-text {
      text-indent: 2em;
      margin: 10px 0;
    }

    :deep(.el-rate) {
      --el-rate-icon-margin: 0;
    }
  }
}

:deep(.el-segmented) {
}

:deep(.el-card__body) {
  padding: 10px;
}

.spec-text {
  border: solid 1px #dcdfe6;
  padding: 5px;
  font-size: 12px;
  border-radius: 5px;

  &:hover {
    border: solid 1px #c6e2ff;
    background-color: #ecf5ff;
    color: #409eff;
  }
}

.spec-text-click {
  border: solid 1px #c6e2ff;
  background-color: #ecf5ff;
  color: #409eff;
}
</style>
